package com.hdjk.view.activity.financial;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.hdjk.view.R;
import com.hdjk.view.adapter.FundListAdapter;
import com.hdjk.view.callback.CallBackListener;
import com.hdjk.view.entity.FundEntity;
import com.hdjk.view.network.FundNetWork;
import com.hdjk.view.util.EmptyViewUtils;
import com.hdjk.view.util.ToastUtils;
import com.hdjk.view.util.UserTokenUtil;
import com.hdjk.view.util.ValidateUtil;
import com.lst.projectlib.base.BaseActivity;
import com.lst.projectlib.entity.Msg;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cn.finalteam.loadingviewfinal.DefaultLoadMoreView;
import cn.finalteam.loadingviewfinal.ListViewFinal;
import cn.finalteam.loadingviewfinal.OnDefaultRefreshListener;
import cn.finalteam.loadingviewfinal.OnLoadMoreListener;
import cn.finalteam.loadingviewfinal.PtrClassicFrameLayout;
import cn.finalteam.loadingviewfinal.PtrFrameLayout;

/**
 * 基金列表页
 * Created by sxy on 2017/11/2.
 */

public class FundListActivity extends BaseActivity implements View.OnClickListener {

    private List<FundEntity> mList;
    private FundListAdapter mAdapter;
    private int mPageIndex = 0;
    private String searchContent = "";

    // Content View Elements
    private com.lst.projectlib.component.CustomView.TopTitleBar ttb_title_bar;
    private PtrClassicFrameLayout ptr_layout;
    private FrameLayout mFlEmptyView;
    private ImageView iv_search;
    private TextView tv_search;
    private EditText et_content;
    private ListViewFinal lv_fund;
    // End Of Content View Elements

    private void bindViews() {
        ttb_title_bar = (com.lst.projectlib.component.CustomView.TopTitleBar) findViewById(R.id.ttb_title_bar);
        ptr_layout = (PtrClassicFrameLayout) findViewById(R.id.ptr_layout);
        mFlEmptyView = (FrameLayout) findViewById(R.id.fl_empty_view);
        iv_search = (ImageView) findViewById(R.id.iv_search);
        tv_search = (TextView) findViewById(R.id.tv_search);
        et_content = (EditText) findViewById(R.id.et_content);
        lv_fund = (ListViewFinal) findViewById(R.id.lv_fund);
    }


    @Override
    protected void initView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_fund_list);
        bindViews();
        ttb_title_bar.findViewById(R.id.tvNavBack).setOnClickListener(this);
        mFlEmptyView.setOnClickListener(this);
        ttb_title_bar.setFocusable(true);
        ttb_title_bar.setFocusableInTouchMode(true);
        ttb_title_bar.requestFocus();
        ttb_title_bar.requestFocusFromTouch();
        tv_search.setOnClickListener(this);
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(et_content, InputMethodManager.SHOW_FORCED);
    }

    @Override
    protected void initData() {
        mList = new ArrayList<>();
        mAdapter = new FundListAdapter(this);
        mAdapter.setDataList(mList);
        lv_fund.setLoadMoreView(new DefaultLoadMoreView(this));
        lv_fund.setAdapter(mAdapter);
        lv_fund.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                int index = (int) id;
                Intent intent = new Intent(FundListActivity.this, FundDetailActivity.class);
                intent.putExtra("id", mList.get(index).getFundCode());
                intent.putExtra("type",FundDetailActivity.TYPE_FUND);
                startActivity(intent);
            }
        });
        lv_fund.setEmptyView(mFlEmptyView);

        ptr_layout.setOnRefreshListener(new OnDefaultRefreshListener() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                // 下拉刷新
                getNetworkList(true);
            }
        });
        ptr_layout.setLastUpdateTimeRelateObject(this);
        lv_fund.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void loadMore() {
                // 上拉加载
                getNetworkList(false);
            }
        });

        et_content.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View view, int i, KeyEvent keyEvent) {
                if (i == KeyEvent.KEYCODE_ENTER) {
                    // 先隐藏键盘
                    ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
                            .hideSoftInputFromWindow(FundListActivity.this.getCurrentFocus()
                                    .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    //进行搜索操作的方法，在该方法中可以加入mEditSearchUser的非空判断
                    searchContent = et_content.getText().toString();
                    getNetworkList(true);
                } else if (i == KeyEvent.KEYCODE_BACK) {
                    ToastUtils.showShortToast(FundListActivity.this, "aaaaaaa");
                }
                return false;
            }
        });
        getNetworkList(true);
    }

    private void onLoaded() {
        ptr_layout.onRefreshComplete();
        lv_fund.onLoadMoreComplete();
    }

    private void getNetworkList(final boolean isDropDown) {
        mDialog.show();
        if (isDropDown) {
            mPageIndex = 1;
        }
        JSONObject object = new JSONObject();
        try {
            object.put("isBuyEnable", "0");
            if (!TextUtils.isEmpty(searchContent)) {
                if (ValidateUtil.isWordNum(searchContent)) {
                    object.put("fundCodes", searchContent);
                } else {
                    object.put("shortName", searchContent);
                }
            }
            object.put("sort", "DESC");
            object.put("period", "year1");
            object.put("pageIndex", mPageIndex);
            object.put("pageSize", 10);
            FundNetWork.getFundList(UserTokenUtil.getToken(FundListActivity.this), object.toString(), new CallBackListener() {
                @Override
                public void onCallBackCompleted(Msg msg) {
                    onLoaded();
                    mDialog.dismiss();
                    if (msg != null && msg.getSuccess() && msg.getData() != null) {
//                        if (TextUtils.isEmpty(msg.getData().toString())) {
//                            lv_fund.setHasLoadMore(false);
//                        } else {
                            List<FundEntity> tempList = (ArrayList) msg.getData();
                            if (null != tempList) {
                                mPageIndex += 1;
                                if (isDropDown) {
                                    mList = tempList;
                                } else {
                                    mList.addAll(tempList);
                                }

                                if (mAdapter == null) {
                                    mAdapter = new FundListAdapter(FundListActivity.this);
                                    mAdapter.setDataList(mList);
                                    lv_fund.setAdapter(mAdapter);
                                } else {
                                    mAdapter.setDataList(mList);
                                    mAdapter.notifyDataSetChanged();
                                }
                                lv_fund.setHasLoadMore(true);
                            }
                            if (null == tempList || (tempList.size() >= 0 && tempList.size() < 10)) {
                                lv_fund.setHasLoadMore(false);
                            }
//                        }
                    }
                    if (mList == null || mList.size() <= 0) {
                        EmptyViewUtils.showNoDataEmpty(mFlEmptyView);
                        return;
                    }
                }

                @Override
                public void onCallBackError(Msg msg) {
                    mDialog.cancel();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tvNavBack:
                back();
                break;
            case R.id.fl_empty_view:
                getNetworkList(true);
                break;
            case R.id.tv_search:
                searchContent = et_content.getText().toString();
                getNetworkList(true);
                break;
        }
    }
}
